<?php
    // This is used to upload a file thru AJAX.
    // INPUT: $_POST[]
    //
    // OUTPUT: Return text passed (encoded via htmlspecialchars)
    // SIDE EFFECT: Store _POST in database after authenticating user permissions


    require_once("../../../includes.php");
    require_once("../model/resource.php");
    require_once("../model/artifact.php");
    require_once("../model/page.php");
    require_once("../model/decoration.php");
    require_once("../model/user.php");

    global $CFG;

    if ( !isloggedin() ) {
        trigger_error('You must be logged in to use this page', E_USER_ERROR);
    }

    // Orienting data
    $page_ident = intval( required_param('page_ident' ) );
    $page = folio_page::SelectWherePageIdent( $page_ident );
    $profile_id = intval( $_SESSION['userid'] );

    // Validate permissions
    if ( !$page->Permission('update') ) {
        trigger_error('You do not have permission to edit this page', E_USER_ERROR);
    }

    // Load the owner of the page (community)
    $user = folio_user::SelectWhereIdent( $page->user_ident);

    $profile_id = $user->ident;
    $ul_username = $user->username;

    // not sure if this is needed, but I'm following the /mod/files/lib/files_action.php
    //      template for uploading files.
    require_once($CFG->dirroot.'lib/uploadlib.php');


    // Get quota information
    $total_quota = get_field_sql("SELECT sum(size) FROM {$CFG->prefix}files WHERE owner = $profile_id");
    $max_quota = user_info('file_quota',$profile_id);
    $maxbytes = $max_quota - $total_quota;


    // Get path information
    $textlib = textlib_get_instance();
    $upload_folder = $textlib->substr($ul_username,0,1);
    $reldir =  "files/" . $upload_folder . "/" . $ul_username . "/";

    // Find what folder to put this into
    $folderid = recordset_to_array(
                get_recordset_sql(
                        "SELECT * FROM {$CFG->prefix}file_folders WHERE files_owner = " .
                        $profile_id . " AND name = 'Portfolio Files'"));

    // If it doesn't already exist, go ahead and create a new folder.
    if ( !$folderid ) {
        $i = new StdClass;
        $i->owner = $profile_id;
        $i->files_owner = $profile_id;
        $i->name = 'Portfolio Files';
        $i->access = 'user' . $profile_id;
        $i->handler = 'elgg';
        $i->parent = -1;
        $folderid = insert_record('file_folders',$i);
    } else {
        foreach( $folderid as $f ) {
            $id = $f->ident;
        }
        $folderid = $id;
    }

    // Upload
    $um = new upload_manager('testFile',false,true,false,$maxbytes,true);

    $f = new StdClass;
    if ($um->process_file_uploads( $CFG->dataroot . $reldir )) {
        $f->owner = $user->ident;
        $f->files_owner = $user->ident;
        $f->folder =  $folderid;
        $f->originalname = $um->get_original_filename();
        $f->title = $um->get_original_filename();
        $f->description = '';
        $f->location = $reldir . $um->get_new_filename();
        $f->access = 'PUBLIC';
        $f->size = $um->get_filesize();
        $f->time_uploaded = time();

        $file_id = insert_record('files',$f);
        $f->ident = $file_id;
    } else {
        trigger_error('Error uploading file.  You may have exceeded your quota, or tried to upload a file larger than the maximum allowed by the server.', E_USER_ERROR);
    }

    $ext = strtoupper(substr( $f->originalname, strlen($f->originalname) - 3 ));
    if( $ext == 'JPG' OR $ext == 'BMP' OR $ext == 'GIF' OR $ext == 'PNG' OR $ext == 'JPG' ) {
        $ext = 'image';
    } else {
        $ext = 'file';
    }

    // Return the file ID
    $file_id = folio_resource::encodeKey( $f->ident, $ext, $profile_id );

    // The js for the rich editor parses values between | and ~ for the key, and
    //      ~ and the end of the line for the page_ident
    echo( "|" . $file_id . "~" . $page_ident );

?>
